<template>
  <view class="moreOrder">
    <!-- #ifdef H5 -->
    <button class="btn-orange" type="default" :plain="true" @click="Jump (22)">打开APP</button>
    <!-- #endif -->
    <view v-if="vuex_loginStatus">
      <u-sticky>
        <u-tabs :line-color="`#FF5533`" :list="statusList" :active-style="activeStyle" :item-style="itemObj" @click="orderStatusClick">
          <view
            v-if="platVal != 1"
            slot="right"
            style="padding-left: 4px;"
            @tap="() => seachFlag = true"
          >
            <u-icon name="list" size="21" bold />
          </view>
        </u-tabs>
        <view v-if="statusCode == 10" class="order-list" style="padding-bottom: 14rpx;width: 100%">
          <view class="radio">
            <view v-for="(item, index) in radioList" :key="index" class="radiobox" :class="platVal == item.code ? 'radioActive' : ''" @click="changeRadio(item.code)">
              {{ item.name }}
              <view class="small">
                <u-icon v-if="platVal == item.code" name="checkmark" color="#FFFFFF" size="8" />
              </view>
            </view>
          </view>
        </view>
      </u-sticky>
      <u-popup :show="seachFlag" mode="right" @close="close" @open="open">
        <view class="search">
          <view v-if="statusCode != 10" class="title">下单渠道</view>
          <view v-if="statusCode != 10" class="SeachTabs">
            <view
              v-for="(item, index) in channelList"
              :key="index"
              :class="channelCode === item.code ? 'defaultTab activeTab' : 'defaultTab'"
              @click="choice(item, 'channel')"
            >{{ item.name }}</view>
          </view>
          <view class="title">交易时间</view>
          <view class="SeachTabs">
            <view
              v-for="(item, index) in timeList"
              :key="index"
              :class="timeCode === item.code ? 'defaultTab activeTab' : 'defaultTab'"
              @click="choice(item, 'time')"
            >{{ item.name }}</view>
          </view>
          <view class="footer">
            <view class="emply" @click="emply">重置</view>
            <view class="confirm" @click="confirmSeach">确认</view>
          </view>
        </view>
      </u-popup>
      <!--      <view v-if="statusCode == 10" style="height: 84rpx" />-->
      <basePage :show-tabbar="true" :page-params="pageParams">
        <view class="order-list" :style="{'paddingTop' : statusCode == 10 ? '0rpx' : '0rpx'}">
          <moreOrderItem
            v-if="platVal == 2"
            :status-code="statusCode"
            :order-res-data="orderResData"
            :cancle-show.sync="cancleShow"
            :cancle-params.sync="cancleParams"
            :date="curDate"
            @reloadList="reloadList"
          />
          <order-list
            v-else
            :order-res-data="orderResData"
            :date="curDate"
            @getOrderListFn="orderStatusClick([])"
          />
          <view class="u-p-b-40">
            <u-loadmore :status="status" />
          </view>
        </view>
      </basePage>
    </view>
    <!-- 未登录显示 -->
    <view v-else>
      <basePage :show-tabbar="true" :page-params="pageParams">
        <view class="login">
          <text>亲，您还没有登录哦～</text>
          <text class="button" @tap="onLoginButtonClick">登录</text>
        </view>
      </basePage>
    </view>
    <!-- 登录弹框 -->
    <u-popup :show="showPopVisible" :round="5" mode="bottom" height="420" @close="closePop">
      <RegisterPop @closePopFn="closePop" />
    </u-popup>
    <canclePop :cancle-show.sync="cancleShow" :cancle-params.sync="cancleParams" @cancelCom="cancelCom" />
  </view>
</template>

<script>
import basePage from '@/components/base-page';
import { getOrderList, cancleOrder, postOrderList } from '@/api/orderApi';
import RegisterPop from '@/components/register-pop';
import { loginMixin } from '@/login/loginMixin';
import OrderList from '@/components/order-list/order-list'
import moreOrderItem from '@/components/order-list/moreOrderItem';
import canclePop from '@/components/order-list/canclePop';
import { queryCreditLinesFn, getSystemTime, formatDate, deepLinkkUrl } from '@/common/common';

export default {
  name: 'Index',
  components: {
    RegisterPop,
    basePage,
    OrderList,
    moreOrderItem,
    canclePop
  },
  mixins: [loginMixin],
  data() {
    return {
      cancleParams: {},
      cancleShow: false, // footer操作取消flag，更新父组件cancleShow，再传递到另外一个子组件
      radioList: [
        { name: '门店订单', code: 1 },
        { name: '平台订单', code: 2 },
      ],
      platVal: 2, // 不可随意更改默认值。涉及到显示何种订单类型
      statusCode: 0,
      orderResData: [],
      current: 0,
      statusList: [
        { name: '全部', code: 0 },
        // { name: '待审批', code: 9 },
        { name: '待处理', code: 10 },
        { name: '待配货', code: 30 },
        { name: '待发货', code: 50 },
        { name: '待收货', code: 60 },
        { name: '待结算', code: 70 },
        { name: '订单成功', code: 80 },
        { name: '订单取消', code: 100 },
        { name: '交易关闭', code: 110 },
      ],
      activeStyle: {
        fontWeight: 600,
        color: '#FF5533'
      },
      itemObj: {
        minWidth: '100rpx',
        height: '44px',
        paddingLeft: '20rpx',
        paddingRight: '20rpx'
      },
      seachFlag: false,
      channelCode: 0,
      channelList: [
        { name: '全部渠道', code: 0 },
        { name: '平台', code: 1 },
        { name: '门店', code: 2 },
      ],
      timeCode: '',
      startTime: '',
      endTime: '',
      timeList: [
        // { name: '1个月内', code: 0 },
        // { name: '3个月内', code: 1 },
        // { name: '6个月内', code: 2 },
        // { name: '今年内', code: 3 },
        // { name: '2021年', code: 4, startTime: '2021-01-01 00:00:00', endTime: '2021-12-31 23:59:59' },
        // { name: '2020年', code: 5, startTime: '2020-01-01 00:00:00', endTime: '2020-12-31 23:59:59' },
        // { name: '2019年', code: 6, startTime: '2019-01-01 00:00:00', endTime: '2019-12-31 23:59:59' },
        // { name: '2018年', code: 7, startTime: '2018-01-01 00:00:00', endTime: '2018-12-31 23:59:59' },
        // { name: '2017年', code: 8, startTime: '2017-01-01 00:00:00', endTime: '2017-12-31 23:59:59' },
      ],
      platformType: '',
      page: 1,
      pageSize: 20,
      orderStatus: [],
      status: 'loading',
      showPopVisible: false,
      pageParams: {
        emptyTitle: '一个订单都没有哦～',
        errorTitle: '请求失败',
        showButton: false,
        state: 'nomore'
      },
      curDate: ''
    }
  },
  watch: {
    vuex_loginStatus: {
      handler(newVal) {
        if (newVal) {
          this.orderStatusClick({ index: 0 })
        }
      }
    }
  },
  onShow() {
    if (this.vuex_loginStatus && this.vuex_accountInfo && this.vuex_accountInfo.loginAccount) {
      this.page = 1
      this.orderResData = []
      this.setPlateformTypeFn()
      this.loadDataFn()
      if (this.platVal == 1 && this.statusCode == 10) {
        this.addList()
      } else {
        this.getOrderList()
      }
    }
    this.setTimeList()
  },
  onReachBottom() {
    this.pageParams.state == 'EMPTY' ? this.page = 1 : this.page++
    this.platVal == 1 ? this.addList() : this.getOrderList()
  },
  onPullDownRefresh: function() {
    this.page = 1
    this.orderResData = []
    this.platVal == 1 ? this.addList() : this.getOrderList()
  },
  mounted() {
    const { accountType } = this.vuex_memberInfo
    var list = [...this.statusList]
    if (Number(accountType) !== 10) {
      list[1].name = '待付款'
      this.statusList = list
    }
  },
  methods: {
    setTimeList() {
      const basicItems = [
        { name: '1个月内', code: 0 },
        { name: '3个月内', code: 1 },
        { name: '6个月内', code: 2 },
        { name: '今年内', code: 3 }
      ]
      const date = new Date()
      const curYear = date.getFullYear()
      const YEAR_LIMITS = 5 // 获取前5年节点
      let i = 0
      while (i < YEAR_LIMITS) {
        const year = curYear - (i + 1)
        const code = basicItems.length
        basicItems.push({ name: `${year}年`, code, startTime: `${year}-01-01 00:00:00`, endTime: `${year}-12-31 23:59:59` })
        i++
      }
      this.timeList = [...basicItems]
    },
    reloadList() { // 提供footer组件刷新页面
      this.page = 1
      this.orderResData = []
      this.platVal == 1 ? this.addList() : this.getOrderList()
    },
    async cancelCom() { // 取消订单
      const res = await cancleOrder(this.cancleParams)
      const toast = () => this.$u.toast('取消成功')
      if (res.code == 0) {
        this.cancleShow = false
        this.orderResData = []
        this.page = 1
        this.cancleParams.cancle_reason = '' // 清空选择
        this.getOrderList(toast)
      } else {
        this.$u.toast(res.message)
      }
    },
    confirmSeach() {
      this.seachFlag = false
      this.reloadList()
    },
    changeRadio(e) {
      this.platVal = e
      this.reloadList()
    },
    emply() {
      this.timeCode = ''
      this.channelCode = 0
      this.startTime = ''
      this.endTime = ''
    },
    open() {},
    close() {
      this.seachFlag = false
    },
    orderStatusClick(item) { // tab切换
      const clickFn = () => {
        this.orderResData = []
        this.page = 1
        this.statusCode = this.statusList[item.index].code
        if (this.statusList[item.index].code == 10) {
          this.platVal = 1
          this.addList()
        } else {
          this.platVal = 2
          this.getOrderList(() => {}, this.statusCode)
        } // tab切换时默认切换为门店订单 // tab切换为待处理时默认平台
      }
      this.$u.debounce(clickFn, 500)
    },
    getMonthBefor(type) {
      var resultDate, year, month, date;
      var currDate = new Date();
      year = currDate.getFullYear();
      month = currDate.getMonth() + 1;
      date = currDate.getDate();
      if (type == 1) {
        switch (month) {
          case 1:
            month += 11;
            year--;
            break;
          default:
            month -= 1;
            break;
        }
      } else if (type == 3) {
        switch (month) {
          case 1:
          case 2:
          case 3:
            month += 9;
            year--;
            break;
          default:
            month -= 3;
            break;
        }
      } else {
        switch (month) {
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
          case 6:
            month += 6;
            year--;
            break;
          default:
            month -= 6;
            break;
        }
      }
      month = (month < 10) ? ('0' + month) : month;
      date = (date < 10) ? ('0' + date) : date;
      resultDate = year + '-' + month + '-' + date;
      return resultDate;
    },
    choice(e, type) {
      type == 'time' ? this.timeCode = e.code : this.channelCode = e.code
      const curentTime = new Date()
      var year = curentTime.getFullYear();
      var month = curentTime.getMonth() + 1;
      var date = curentTime.getDate();
      month = (month < 10) ? ('0' + month) : month;
      date = (date < 10) ? ('0' + date) : date;
      this.timestampToTime(curentTime)
      if (type == 'time') {
        if (e.code == 0) {
          this.startTime = this.getMonthBefor(1) + ' 00:00:00'
          this.endTime = year + '-' + month + '-' + date + ' 23:59:59'
        } else if (e.code == 1) {
          this.startTime = this.getMonthBefor(3) + ' 00:00:00'
          this.endTime = year + '-' + month + '-' + date + ' 23:59:59'
        } else if (e.code == 2) {
          this.startTime = this.getMonthBefor(6) + ' 00:00:00'
          this.endTime = year + '-' + month + '-' + date + ' 23:59:59'
        } else if (e.code == 3) {
          this.startTime = year + '-01-01 00:00:00'
          this.endTime = year + '-12-31 23:59:59'
        } else {
          this.startTime = e.startTime
          this.endTime = e.endTime
        }
      }
    },
    timestampToTime(timestamp) {
      var date = new Date(timestamp);
      var Y = date.getFullYear() + '/';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
      var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
      return Y + M + D;
    },
    setPlateformTypeFn() { // 平台值转化
      if (Object.keys(this.vuex_memberInfo).length == 0) return
      switch (this.vuex_memberInfo.accountType) { // 账户类型：10:签约用户；20:普通用户;30认证用户;39普通会员-分销;40分销用户；
        case 10:
          this.platformType = 1
          break
        case 20:
          this.platformType = 2
          break
        case 30:
          this.platformType = 2
          break
        case 39:
          this.platformType = 3
          break
        case 40:
          this.platformType = 3
          break
        default:
          this.platformType = 2
          break
      }
    },
    async getOrderList(callBack, statusCode) { // 获取平台
      this.status = 'loading'
      const { accountType, memberId, customerId, customerName, loginAccount } = this.vuex_memberInfo
      const params = {
        page_num: this.page,
        page_size: this.pageSize,
        tab_order_status: this.statusCode == 0 ? '' : this.statusCode,
        customer_name: customerName,
        customer_id: customerId,
        member_id: memberId,
        login_account: loginAccount,
        paid_at_begin: '',
        paid_at_end: '',
        account_type: accountType,
        platform: this.channelCode, // 0 全部、 1 门店、 2平台、 只有待付款会有门店订单
        request_source: 10,
        // month_query: 1,
        created_at_begin: this.startTime,
        created_at_end: this.endTime,
        version_code: 10000
      }
      const res = await getOrderList(params)
      if ((statusCode || statusCode == '') && (this.statusCode != statusCode)) return // 如果当前请求Tab值和当前Tab页值不同，请求逻辑不再进行
      const { pageStoreOrderPojoList = {}} = res.data || {}
      if ((!res.data || !pageStoreOrderPojoList || pageStoreOrderPojoList.totalRecord == 0) && this.page == 1) {
        this.pageParams.state = 'EMPTY'
        this.status = 'nomore'
      }
      if (!!pageStoreOrderPojoList.result && pageStoreOrderPojoList.result.length > 0) {
        var filterList = []
        // if (this.statusCode == '' || this.statusCode == 9) { // 全部和待审核状态不显示门店订单
        //   filterList = pageStoreOrderPojoList.result.filter((item) => {
        //     return (item.platform == 10 || item.platform == 20)
        //   })
        // } else {
        filterList = pageStoreOrderPojoList.result
        // }
        this.orderResData = [...this.orderResData, ...filterList]
        this.pageParams.state = 'default'
        this.status = pageStoreOrderPojoList.totalRecord <= 20 ? 'nomore' : 'loadmore'
        uni.stopPullDownRefresh();
      } else {
        this.status = 'nomore'
      }
      callBack && callBack()
    },
    addList() { // 门店
      this.status = 'loading'
      const params = { 'orderStatus': [this.statusCode], 'pageNum': this.page, 'pageSize': this.pageSize }
      postOrderList(params).then((res) => {
        if (res.data != null) {
          if (res.data.result.length != 0) {
            this.pageParams.state = 'default'
            if (this.page == 1) {
              this.orderResData = res.data.result
            } else {
              this.orderResData.push(...res.data.result)
            }
            if (res.data.totalRecord <= 20) {
              this.status = 'nomore'
            }
          } else if (this.page == 1 && res.data.result.length == 0) {
            this.status = ''
            this.pageParams.state = 'EMPTY'
          } else {
            this.status = 'nomore'
          }
          uni.stopPullDownRefresh();
        } else {
          this.status = ''
          this.pageParams.state = 'EMPTY'
        }
      }).catch(() => {
      })
    },
    loadDataFn() {
      // this.orderStatusClick({ index: 0 })
      this.getAccountTimeFn()
    },
    /*获取时间*/
    async getAccountTimeFn() {
      const time = await getSystemTime()
      this.curDate = formatDate(new Date(time), 'yyyy-mm-dd')
    },
    setFormatDate(time) {
      const orderNextTime = formatDate(new Date(new Date(time).getTime() + (24 * 60 * 60 * 1000)), 'yyyy-mm-dd')
      return orderNextTime
    },
    /*获取可用额度*/
    async queryCreditLinesFn(customerNumber) {
      const params = {
        'customerNumber': customerNumber
      }
      const creditLinesData = await queryCreditLinesFn(params)
      return creditLinesData[0].internal_credit_data.internal_credit_avail
    },
    onLoginButtonClick() {
      const callbackUrl = `/pages/order/moreOrder`
      // #ifdef MP-ALIPAY || MP-WEIXIN
      uni.navigateTo({
        url: `../../login/login/codeLogin?type=order&callbackUrl=${callbackUrl}`
      })
      // #endif
      //#ifdef H5
      uni.navigateTo({
        url: `../../login/login/mCodeLogin?type=order&callbackUrl=${callbackUrl}`
      })
      // #endif
    },
    Jump(jumpType) {
      const ua = navigator.userAgent.toLowerCase();
      const versionsios = navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
      let host = ''
      const AurlencodeM = encodeURIComponent('openfs://mfsyuncai?jumpType=' + jumpType + '&jumpVar=' + '{' + '}')
      const IOSurlencodeM = encodeURIComponent('fangshengyuncai://mfsyuncai?jumpType=' + jumpType + '&jumpVar=' + '{' + '}')
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        // this.$u.toast('请用其他浏览器打开app')
        // return
        if (versionsios) { // ios
          window.location.href = 'https://a.app.qq.com/o/simple.jsp?pkgname=com.xfs.fsyuncai&ios_schema=' + IOSurlencodeM
        } else {
          window.location.href = 'http://a.app.qq.com/o/simple.jsp?pkgname=com.xfs.fsyuncai&android_schema=' + AurlencodeM
        }
      } else {
        if (versionsios) { // ios
          host = 'fangshengyuncai://mfsyuncai'
        } else {
          host = 'openfs://mfsyuncai'
        }
        if (jumpType == 22) {
          window.location.href = host + '?jumpType=22' + '&jumpVar=' + '{' + '}'
        }
        setTimeout(function() { //跳转到中间页
          window.location.href = deepLinkkUrl.develop + '/h5/fsyuncai/linkApp.html?isM=1'
        }, 3000)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.order-list {
  background: #F5F5F5;
  padding: 32rpx;
  box-sizing: border-box;
  .radio {
    //padding: 24rpx 0rpx;
    display: flex;
    justify-content: flex-start;
    .radiobox{
      width: 184rpx;
      height: 52rpx;
      border-radius: 8rpx;
      background: #ffffff;
      border: 1rpx solid #ffffff;
      padding: 10rpx 22rpx;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;
      align-content: center;
      margin-right: 24rpx;
      .small {
        width: 24rpx;
        height: 24rpx;
        border: 1rpx solid #D3D3D3;
        border-radius: 50%;
        flex-shrink: 1;
        padding: 0;
        margin: 0;
        display: flex;
        justify-content: center;
        align-content: center;
        align-items: center;
      }
    }
    .radioActive {
      border: 1rpx solid #FF5533;
      color: #FF5533;
      .small {
        background: #FF5533;
        border: 1rpx solid #FF5533;
      }
    }
  }
}
.moreOrder {
   .btn-orange{
     position: fixed;
     right:32rpx;
     top:20rpx;
     z-index: 999;
     height:56rpx!important;
     line-height: 56rpx!important;
     border: 0;
     background: #F53;
     padding:0 28rpx!important;
  }
  .title {
    color:$uni-text-color;
    font-size: 28rpx;
    margin-top: 48rpx;
  }
  .SeachTabs {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  .activeTab {
    color: #FF5533;
    border: 2rpx solid #FF5533 !important;
    background: #FFFFFF !important;
  }
  .defaultTab {
    width: 178rpx;
    height: 62rpx;
    border-radius: 8rpx;
    background: #F5F5F5;
    display: flex;
    justify-content: center;
    align-content: center;
    align-items: center;
    margin-top: 16rpx;
    margin-right: 16rpx;
    border: 2rpx solid #F5F5F5;
    box-sizing: border-box;
  }
  .defaultTab:nth-child(3n + 3) {
    margin-right: 0rpx;
  }
  .search {
    width: 670rpx;
    height: 100%;
    position: relative;
    box-sizing: border-box;
    padding: 0rpx 48rpx;
    .footer {
      position: absolute;
      bottom: 90rpx;
      left: 0rpx;
      width: 100%;
      padding: 0rpx 48rpx;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-content: center;
      align-items: center;
      font-size: 32rpx;
      .emply {
        width: 180rpx;
        height: 68rpx;
        border-radius: 8rpx;
        border: 1px solid #D3D3D3;
        display: flex;
        justify-content: center;
        align-items: center;
        align-content: center;
      }
      .confirm {
        width: 360rpx;
        height: 68rpx;
        border-radius: 8rpx;
        background: rgba(255,85,51,1);
        display: flex;
        justify-content: center;
        align-items: center;
        align-content: center;
        color: #FFFFFF;
      }
    }
  }
}
/deep/ .u-tabs {
  background: #FFFFFF;
  padding-right: 20rpx;
  box-sizing: border-box;
}
page {
  background-color: #f8f8f8;
}
.login {
  display: flex;
  align-items: center;
  padding-top: 28px;
  flex-direction: column;
  background-color: white;
  font-size: 16px;
  color: #333333;
  text-align: center;
  font-weight: 400;
}

.button {
  width: 92px;
  height: 24px;
  margin-top: 28px;
  margin-bottom: 36px;
  background: $uni-orange;
  border-radius: 12px;
  font-size: 12px;
  color: #fff;
  text-align: center;
  align-items: center;
  justify-content: center;
  display: flex;
}
</style>
